from mt4_client import MT4Client
import time
from datetime import datetime

def monitor_prices():
    """监控价格变动"""
    client = None
    try:
        client = MT4Client()
        
        # 订阅价格更新
        symbol = "ETHUSD"
        print(f"订阅 {symbol} 的价格更新...")
        response = client.subscribe_price(symbol)
        print(f"订阅结果: {response}")
        
        print(f"\n开始监控 {symbol} 的价格变动...")
        print("按 Ctrl+C 停止监控")
        
        while True:
            # 获取价格更新
            price_update = client.get_price_update()
            
            if price_update:
                # 打印价格信息
                timestamp = datetime.fromtimestamp(price_update["time"])
                print(f"\n时间: {timestamp}")
                print(f"货币对: {price_update['symbol']}")
                print(f"买价: {price_update['bid']}")
                print(f"卖价: {price_update['ask']}")
                print(f"点差: {price_update['ask'] - price_update['bid']}")
                
                # 这里可以添加你的交易逻辑
                # 例如：检查价格是否达到某个条件，然后开仓或平仓
                
            # 短暂休眠，避免CPU占用过高
            time.sleep(0.001)
            
    except KeyboardInterrupt:
        print("\n停止监控...")
    except Exception as e:
        print(f"发生错误: {str(e)}")
    finally:
        if client:
            # 取消订阅
            print(f"\n取消订阅 {symbol}...")
            response = client.unsubscribe_price(symbol)
            print(f"取消订阅结果: {response}")
            
            # 关闭连接
            print("关闭连接...")
            client.close()

if __name__ == "__main__":
    monitor_prices() 